<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {deleteTypeSet, findTypeSets} from "@/apis/zyj/typeSetting.js";
import addType from "@/components/TypeSetting/AddDialog.vue"
import updateType from "@/components/TypeSetting/UpdateDialog.vue"

const searchForm = reactive({
  typeCode: '',
  typeName: '',
  maintenanceType: ''
})

const form = reactive({
  typeCode: '',
  typeName: '',
  isCodeManaged: false,
  maintenanceType: '',
  maintenancePeriod: '',
  remark: ''
})


function initData() {
  findTypeSets(searchForm.typeCode, searchForm.typeName, searchForm.maintenanceType, 1, 10).then(res => {
    console.log(res)
    tableData.value = res.records
    total.value = res.total
    currentPage.value = res.current;
  })
}

onMounted(() => {
  initData()
})

const tableData = ref([])
const addDialog = ref(false)
const updateDialog = ref(false)//修改对话框
const select_order_number = ref('') //表格select选中的条数
const select_orderId = ref([]) //表格select复选框选中的id
const multipleSelection = ref()//选中行的数据
const multipleTable = ref()//用于表格多选框选中的清理
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(1)
const onSearch = () => {
  initData()
}

const onReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
}

const onAdd = () => {
  addDialog.value = true
}

const onModify = (row) => {
  updateDialog.value = true
  if (row.typeCode != null) {
    multipleSelection.value = {...row}
  } else {
    multipleSelection.value = {...multipleSelection.value[0]}
  }
}


const onExport = () => {
  ElMessage.success('导出功能已触发')
}

const handleDelete = (row) => {
  if (row.typeCode != null) {
    select_order_number.value = "1";
  } else {
    select_order_number.value = multipleSelection.value.length;
  }
  console.log(select_orderId.value)
  ElMessageBox.confirm(
      '是否要删除 ' + select_order_number.value + '条数据',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        if (row.typeCode != null) {
          select_orderId.value = [];
          select_orderId.value.push(row.typeCode)
        }
        deleteTypeSet(select_orderId.value).then((res) => {
          if (res == '成功') {
            initData()
            ElMessage.success('成功删除: ' + select_order_number.value + '条数据')
            select_order_number.value = "0";
            select_orderId.value = [];
            multipleTable.value.clearSelection();
          } else {
            ElMessage.error('系统错误！删除失败')
          }
        })
      })
      .catch(() => {
        ElMessage.info('删除取消')
      })
}

const handleSizeChange = (val) => {
  initData()
}

const handleCurrentChange = (val) => {
  initData()
}

//选中事件
const handleSelectionChange = (val) => {
  // 解决来回切换页面，也无法清除上次选中情况
  multipleSelection.value = val;
  select_order_number.value = multipleSelection.value.length;
  select_orderId.value = [];
  if (val) {
    val.forEach((row) => {
      if (row) {
        select_orderId.value.push(row.typeCode);
      }
    });
  }
}

const closeDialog = () => {
  addDialog.value = false
  updateDialog.value = false
  initData()
}
</script>

<template>
  <div class="data-management">
    <el-card>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="类型编码">
          <el-input v-model="searchForm.typeCode" placeholder="请输入类型编码" clearable/>
        </el-form-item>
        <el-form-item label="类型名称">
          <el-input v-model="searchForm.typeName" placeholder="请输入类型名称" clearable/>
        </el-form-item>
        <el-form-item label="保养维护类型">
          <el-select v-model="searchForm.maintenanceType" placeholder="请选择保养维护类型" clearable
                     style="width: 180px">
            <el-option label="定期维护" value="定期维护"/>
            <el-option label="按使用次数维护" value="按使用次数维护"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">搜索</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top: 20px">
      <div class="action-buttons">
        <el-button type="primary" @click="onAdd" plain>新增</el-button>
        <el-button type="success" @click="onModify" :disabled="select_order_number!=1" plain>修改</el-button>
        <el-button type="danger" @click="handleDelete" :disabled="select_order_number==0" plain>删除</el-button>
      </div>

      <el-table :data="tableData" style="width: 100%" max-height="380px" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="typeCode" label="类型编码"/>
        <el-table-column prop="typeName" label="类型名称"/>
        <el-table-column prop="isCodeManaged" label="是否编码管理">
          <template #default="scope">
            <el-tag :type="scope.row.isCodeManaged == '0' ? 'success' : 'error'">
              {{ scope.row.isCodeManaged == '0' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="maintenanceType" label="保养维护类型">
          <template #default="scope">
            {{ scope.row.maintenanceType == null ? '无' : scope.row.maintenanceType }}
          </template>
        </el-table-column>
        <el-table-column prop="maintenancePeriod" label="保养周期">
          <template #default="scope">
            {{ scope.row.maintenancePeriod == null ? '无' : scope.row.maintenancePeriod }}
            {{
              scope.row.maintenanceType == '定期维护' ? '天' : (scope.row.maintenanceType == '按使用次数维护' ? '次' : '')
            }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注"/>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="onModify(scope.row)">修改</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 40]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <add-type :addDialog="addDialog" @close-dialog="closeDialog"/>
    <update-type :updateDialog="updateDialog" :form="multipleSelection" @close-dialog="closeDialog"/>
  </div>
</template>

<style scoped>
.data-management {
  padding: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: left;
}

.el-pagination {
  justify-content: flex-end;
}

</style>